<template>
  <div v-loading="loading" style="height: 100%">
    <van-nav-bar :right-text="postingDate"
                 left-arrow left-text="返回"
                 title="吨槽发出信息"
                 @click-left="goBack"
                 @click-right="setPostDate"/>
    <van-cell-group :v-model="tableData"
                    style="overflow:
                    scroll;
                    height: 520px">
      <van-field ref="code_input"
                 v-model="code_input"
                 left-icon="scan"
                 placeholder="请扫描条码"
                 @input="onSubmitScanResult"/>
      <van-divider content-position="left" style="height: 2px; font-style: italic">信息</van-divider>
      <van-row style="border: solid 1px #3793fb; border-radius: 5px">
        <van-col span="24">
          <el-autocomplete id="autocomplete"
                           v-model="tableData.zzcys" :fetch-suggestions="supplierSearchPart"
                           :rules="{
                             required: true,
                             message: '请选择运输公司',
                             trigger: 'blur',}"
                           label="运输公司"
                           placeholder="运输公司" style="width: 100%"
                           value-key="codeanddes"></el-autocomplete>
        </van-col>
      </van-row>
      <van-field
          :value="tableData.carNo"
          label="车牌号"
          @click="show = true"
          style="border: solid 1px #3793fb; border-radius: 5px"
      />
      <vnp-keyboard v-model="tableData.carNo"
                    @input="carNoStatus" :show.sync="show" ></vnp-keyboard>

      <van-row style="border: solid 1px #3793fb; border-radius: 5px">
        <van-col span="24">
          <el-autocomplete id="autocompletePlant"
                           v-model="tableData.plant" :fetch-suggestions="plantSearchPart"
                           :rules="{
                      required: true,
                      message: '请选择工厂',
                      trigger: 'blur',}"
                           label="接收工厂"
                           placeholder="工厂" style="width: 100%;"
                           value-key="plantname"></el-autocomplete>
        </van-col>
      </van-row>
      <van-field v-for="(item, index) in tableData.details" :key="index" v-model="item.quantity"
                    label="桶数：" readonly/>
      <van-collapse v-model="activeNames">
        <van-field v-for="(item, index) in tableData.recycledata" :key="index" v-model="item.numberofbarrels"
                    label="桶号：" readonly/>
      </van-collapse>
    </van-cell-group>
    <van-button block
                style="position: fixed; bottom: 0px; border: #3793fb solid 1px; border-radius: 2px; background-color: #3793fb; line-height: var(--footer-height)"
                type="primary" @click="onSubmit">吨槽发出
    </van-button>
  </div>
</template>

<script>
import Keyboard from '../../assets/views/vnp-keyboard.vue';

export default {
  components: {'vnp-keyboard': Keyboard},
  data() {
    return {
      activeNames: ['1'], // 默认展开第一项
      supplierSearchListPart: [],
      plantList: [],
      tableData: {
        recycledata: [],
        details: [],
      },
      loading: false,
      showKeyboards: false,
      showCalendar: false,
      postingDate: this.getNowFormatDate(new Date()),
      activeName: '1',
      code_input: '',
      show: false
    };
  },
  mounted() {
    //获取运输公司
    this.getSupplierSearchList();
    //获取工厂
    this.getPlantList();
  },
  methods: {
    onSubmitScanResult(event) {
      this.getBucket(event);
    },
    carNoStatus(){
      this.getcarNo();
    },
    async getcarNo() {
      let scanInfo = {
        plant: this.tableData.zzcys,
        carNo: this.tableData.carNo,
      };
      const { data: Status } = await this.$http.post(
          "/CarNoList",
          scanInfo
      );
      var response = Status[0];
      if (response.type == "E") {
        this.$message({
          message: response.message,
          type: "error",
        });
        this.tableData.carNo = '';
      }
    },
    async getBucket(bucketNo) {
      let scanInfo = {
        code: bucketNo,
      };
      const {data: res} = await this.$http.post(
          "/ToneSlotsSend",
          scanInfo
      );
      console.log("res", res);
      if (res.length && res[0].numberofbarrels) {
        var requestData = this.tableData;
        for (var i in requestData.recycledata) {
          if (requestData.recycledata[i].numberofbarrels === res[0].numberofbarrels) {
            this.$message({
              message: "扫描失败，请勿重复扫描同一桶号",
              type: "error",
            });
            this.code_input = '';
            return
          }
        }
        if ('空闲' !== res[0].bucketstatus) {
          this.$toast.fail('条码信息错误,非空闲状态');
          this.code_input = '';
          return
        }
        this.code_input = '';
        this.tableData.recycledata.push(res[0]);
        var newQuantity = 1;
        for (let i in requestData.details) {
          // if(requestData.details[i].numberofbarrels === res[0].numberofbarrels){
            requestData.details[i].quantity = Number(requestData.details[i].quantity) + 1 ;
            return
          // }
        }
        this.tableData.details.push({ quantity: newQuantity });
      } else {
        this.code_input = '';
        this.$toast.fail('条码信息错误');
      }
    },
    setPostDate() {
      this.showCalendar = true;
    },
    getcrNumber(val) {
      const carNumberReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;
      if (carNumberReg.test(val)) {
        this.showKeyboards = false;
        this.carNumber = val;
      }
    },
    async getSupplierSearchList() {
      let suppInfo = {
        plant: localStorage.getItem("supplier"),
      };
      const {data: res} = await this.$http.post(
          "/SupplierList",
          suppInfo
      );
      this.supplierSearchListPart = res;
    },
    async getPlantList() {
      let scanInfo = {};
      const {data: res} = await this.$http.post(
          "/PlantList",
          scanInfo
      );
      this.plantList = res;
    },
    //工厂搜索帮助
    plantSearchPart(queryString, cb) {
      var plantList = this.plantList;
      var results = queryString
          ? plantList.filter(this.createFilter(queryString))
          : plantList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //运输公司搜索帮助
    supplierSearchPart(queryString, cb) {
      var supplierSearchList = this.supplierSearchListPart;
      var results = queryString
          ? supplierSearchList.filter(this.supplierFilter(queryString))
          : supplierSearchList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    supplierFilter(queryString) {
      return (storageLocation) => {
        return (
            storageLocation.codeanddes
                .toLowerCase()
                .indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    createFilter(queryString) {
      return (storageLocation) => {
        return (
            storageLocation.plantname
                .toLowerCase()
                .indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    //返回
    goBack() {
      this.$router.push('/HomePage');
    },
    //入库过账
    onSubmit() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        this.postToneSlotsSend();
      }, 1000);
      this.dialogVisible = false;
    },
    //过账接口
    async postToneSlotsSend() {
      var requestData = this.tableData;
      console.log("requestData", requestData);
      console.log("localStorage", localStorage);
      let inputInfo = {
        plant: requestData.plant.split("|")[0],
        persnumber: localStorage.getItem("erpId"),
        postdate: this.postingDate,
        zzcys: requestData.zzcys.split("|")[0],
        zzcysDes: requestData.zzcys.split("|")[1],
        carNo: requestData.carNo,
        // location: requestData.location.split("|")[0],
        recycledata: requestData.recycledata,
      };
      console.log("inputInfo", inputInfo)
      const {data: res} = await this.$http.post(
          "/ToneSlotsSendPost",
          inputInfo
      );
      var response = res[0];
      if (response.type == "S") {
        this.$toast.success(response.message);
        setTimeout(() => {
          this.$router.push("/HomePage");
        }, 1000);
      } else if (response.type == "E") {
        this.$message({
          message: response.message,
          type: "error",
        });
      } else {
        this.$message({
          message: "入库失败，请联系系统维护人员",
          type: "error",
        });
      }
    },
  }
};
</script>
<style></style>
